package com.tgjorgoski.sidekicknotes.filedata;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.util.Date;
import java.util.List;

import javax.persistence.*;

import com.tgjorgoski.utils.FileMethods;
import com.tgjorgoski.window.Session;

@Entity
public class FileInformation {
	public static int SPELLCHECK_USE=1, SPELLCHECK_DONT_USE=0, SPELLCHECK_DEFAULT=2;
	
	private long id;
	private String fileName;
	private List<Category> categories;
	private int useSpellCheck=SPELLCHECK_DEFAULT;
	private Date lastOpened;
	private Date lastModified;
	
	@Id @GeneratedValue(strategy=GenerationType.AUTO)
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}

	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}


	@OneToMany(cascade = CascadeType.PERSIST)
	@JoinTable(joinColumns = { @JoinColumn(name = "file_id") }, inverseJoinColumns = @JoinColumn(name = "category_id"))
	public List<Category> getCategories() {
		return categories;
	}
	public void setCategories(List<Category> categories) {
		this.categories = categories;
	}
	public int getUseSpellCheck() {
		return useSpellCheck;
	}
	public void setUseSpellCheck(int useSpellCheck) {
		this.useSpellCheck = useSpellCheck;
	}
	public void setLastOpened(Date lastOpened) {
		this.lastOpened = lastOpened;
	}
	@Column(nullable=true)
	public Date getLastOpened() {
		return lastOpened;
	}
	public void setLastModified(Date lastModified) {
		this.lastModified = lastModified;
	}
	@Column(nullable=true)
	public Date getLastModified() {
		return lastModified;
	}

	public static void renamed(String oldName, String newName) {
		FileInformation fi = Session.getPersistManager().getBean(FileInformation.class, "filename", oldName);
		if (fi!=null) {
			fi.setFileName(newName);
			Session.getPersistManager().saveObject(fi);
		}
	}

	public static FileInformation getFileInformation(File f) {
		String normalizedURL = FileMethods.getNormPath(f);
		FileInformation fi = Session.getPersistManager().getBean(FileInformation.class, "filename", normalizedURL);
		if (fi==null) {
			fi = new FileInformation();
			fi.fileName=normalizedURL;
			fi.useSpellCheck=SPELLCHECK_DEFAULT;
			//Maybe we can get modified value from lucene, but no biggy if we don't
			Session.getPersistManager().saveObject(fi);
		}
		return fi;
	}
}
